package main

import (
	"bufio"
	"fmt"
	"net"
	"os/exec"
	"strings"
)

func main() {
	// 定义服务器地址和端口
	serverAddr := "localhost:8080"

	// 创建 TCP 监听器
	listener, err := net.Listen("tcp", serverAddr)
	fmt.Printf("starting listen\n")
	if err != nil {
		fmt.Printf("Error starting server: %v\n", err)
		return
	}
	defer listener.Close()

	fmt.Printf("Server listening on %s\n", serverAddr)

	for {
		// 接受客户端连接
		conn, err := listener.Accept()
		fmt.Printf("get accept\n")
		if err != nil {
			fmt.Printf("Error accepting connection: %v\n", err)
			continue
		}

		// 处理客户端连接
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	// 创建 bufio.Reader 以便逐行读取数据
	reader := bufio.NewReader(conn)

	for {
		// 读取一行数据
		line, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("Error reading from connection: %v\n", err)
			break
		}

		// 去除行尾的换行符
		line = strings.TrimSpace(line)
		fmt.Printf("get msg script: %s\n", line)

		// 执行消息指定的脚本
		err = executeScript(line)
		fmt.Printf("exe script: %s\n", line)
		if err != nil {
			fmt.Printf("Error executing script: %v\n", err)
			break
		}
	}
}

func executeScript(command string) error {
	// 使用 os/exec 包执行命令
	cmd := exec.Command("sh", "-c", command)

	// 将命令的输出重定向到标准输出
	cmd.Stdout = nil
	cmd.Stderr = nil

	// 启动命令
	fmt.Printf("run script: %s\n", command)
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("failed to execute command: %v", err)
	}
	fmt.Printf("finish script: %s\n", command)

	return nil
}
